package org.example.com.editor.command.editorCommand;

import org.example.com.editor.command.Command;
import org.example.com.editor.command.Undoable;
import org.example.com.editor.command.commandHistory.CommandHistoryItem;
import org.example.com.editor.editor.Editor;
import org.example.com.editor.editor.TextEditor;
import org.example.com.editor.logger.LogManager;
import org.example.com.editor.ui.ConsoleUI;
import org.example.com.editor.workspace.Workspace;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ReplaceCommand implements Command, Undoable {
    private final LogManager logManager;

    public ReplaceCommand(LogManager logManager) {
        this.logManager = logManager;
    }

    @Override
    public void execute(Workspace workspace, ConsoleUI ui) {
        Map<String, Object> params = new HashMap<>();
        TextEditor editor = (TextEditor) workspace.getActiveEditor();
        if (editor == null) {
            ui.printError("没有活动文件，请先打开或新建文件");
            return;
        }

        String[] args = ui.getCommandArgs();
        if (args.length != 4) {
            ui.printError("用法：replace <line:col> <长度> \"替换文本\"");
            return;
        }

        // 解析行号和列号
        String[] lineCol = args[1].split(":", 2);
        if (lineCol.length != 2) {
            ui.printError("位置格式错误，请使用\"行号:列号\"（例如：1:1）");
            return;
        }

        int lineNum, colNum, len;
        String text;
        try {
            lineNum = Integer.parseInt(lineCol[0]);
            colNum = Integer.parseInt(lineCol[1]);
            len = Integer.parseInt(args[2]);
        } catch (NumberFormatException e) {
            ui.printError("行号、列号和长度必须是整数");
            return;
        }

        // 解析替换文本
        String rawText = args[3];
        if (rawText.length() < 2 || !rawText.startsWith("\"") || !rawText.endsWith("\"")) {
            ui.printError("替换文本必须用双引号包裹（例如：\"slow\"）");
            return;
        }
        text = rawText.substring(1, rawText.length() - 1);

        // 执行替换前获取原行长度
        String targetLine = editor.getContent().get(lineNum - 1);
        int originalLineLength = targetLine.length();

        // 执行替换
        String originalText = editor.replace(lineNum, colNum, len, text);

        // 完整存储所有参数（Key名称与undo/redo时一致）
        params.put("lineNum", lineNum);
        params.put("colNum", colNum);
        params.put("len", len);
        params.put("text", text);
        params.put("originalText", originalText);
        params.put("originalLineLength", originalLineLength); // 存储原行长度

        editor.recordCommand(new CommandHistoryItem(this, params));

        try {
            logManager.onCommandExecuted(workspace.getActiveFile(), args);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void undo(Editor editor, ConsoleUI ui, Map<String, Object> params) {
        // 空值校验
        Integer lineNum = (Integer) params.get("lineNum");
        Integer colNum = (Integer) params.get("colNum");
        String originalText = (String) params.get("originalText");
        String text = (String) params.get("text");
        Integer originalLineLength = (Integer) params.get("originalLineLength");

        if (lineNum == null || colNum == null || originalText == null || text == null || originalLineLength == null) {
            ui.printError("撤销替换操作失败：参数不完整");
            return;
        }

        try {
            ((TextEditor) editor).undoReplace(lineNum, colNum, originalText, text, originalLineLength);
        } catch (Exception e) {
            ui.printError("撤销替换操作失败：" + e.getMessage());
        }
    }

    @Override
    public void redo(Workspace workspace, ConsoleUI ui, Map<String, Object> params) {
        // redo从params取参
        Integer lineNum = (Integer) params.get("lineNum");
        Integer colNum = (Integer) params.get("colNum");
        Integer len = (Integer) params.get("len");
        String text = (String) params.get("text");

        if (lineNum == null || colNum == null || len == null || text == null) {
            ui.printError("重做替换操作失败：参数不完整");
            return;
        }

        TextEditor editor = (TextEditor) workspace.getActiveEditor();
        if (editor != null) {
            editor.replace(lineNum, colNum, len, text);
        }
    }

    @Override
    public String getName() {
        return "replace";
    }

    // 移除冗余的replace方法，直接调用editor的replace
}